package tech.aistar.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.ModelAndView;
import tech.aistar.entity.Car;
import tech.aistar.service.ICarService;

import javax.websocket.server.PathParam;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lpy
 * @since 2022-11-12
 */
@Controller
public class CarController {
    @Autowired
    private ICarService carService;

    @GetMapping("car")
    public ModelAndView getALl(){
        List<Car> carList=carService.list();
        System.out.println("success!");
        ModelAndView mav = new ModelAndView();
        mav.addObject("carList",carList);
        mav.setViewName("car/list");
        return mav;
    }

    @GetMapping("car/getByID")
    public ModelAndView getById(@RequestParam("carId") Integer carId){
        Car car=carService.getById(carId);
        ModelAndView mav = new ModelAndView();
        mav.addObject("car",car);
        mav.setViewName("car/detail");
        return mav;
    }

    @PostMapping("car/save")
    public ModelAndView save(Car car){
        boolean request=carService.save(car);
        ModelAndView mav = new ModelAndView();
        if(request){
            mav.addObject("msg","新增一条信息");
            mav.setViewName("car/msg");
        }
        else{
            mav.addObject("msg","新增失败！");
            mav.setViewName("car/msg");
        }
        return mav;
    }

    @GetMapping("car/page/{pagenum}")
    public ModelAndView getByPage(@PathVariable Integer pagenum){
        ModelAndView mav = new ModelAndView();
        Page<Car> pageInfo=carService.getByPage(pagenum);
        mav.addObject("pageInfo",pageInfo);
        mav.setViewName("car/all");
        return mav;
    }

    @DeleteMapping("car")
    @ResponseBody
    public Boolean delete(@RequestParam("carId") Integer carId){
        boolean result = carService.removeById(carId);
        System.out.println("删除后:" + carId + ", result:" + result);
        return result;
    }

    @GetMapping("car/{carId}")
    public ModelAndView update(@PathVariable("carId") Integer carId){
        ModelAndView mav = new ModelAndView();
        Car car = carService.getById(carId);
        mav.addObject("car",car);
        mav.setViewName("car/update");
        return mav;
    }

    //修改用户信息:  2. 修改用户信息
    @PutMapping("car")
    @ResponseBody
    public boolean update(Car car){
        boolean result  =carService.updateById(car);
        return result;
    }
}
